<template>
  <div>
    websocketTest <br />
    <messageScreen v-model="receive"></messageScreen>
    <a-row>
      <span> 发送区:</span>
      <a-textarea v-model="msg" :rows="4" style="width: 400px; height: 200px" />
      <a-button type="primary" @click="handleSend">发送</a-button>
      <a-button type="primary" @click="clearMessage">清空</a-button>
      <a-button type="primary" @click="initSocket">手动连接</a-button>
      <a-button type="primary" @click="closeConnect">关闭连接</a-button>
    </a-row>
  </div>
</template>

<script setup>
let maxTry = 3
var socketUrl = 'ws://6d3618fa.r26.cpolar.top/ws/monitor'
var socket = null
const msg = ref('')
const receive = ref('')
const userId = '1835979905138909185' // 用户ID
onMounted(() => {
  maxTry = 3
  initSocket()
})
const handleSend = () => {
  socket.send(msg.value)
  console.log('send', msg.value)
}
const clearMessage = () => {
  receive.value = ''
}
const closeConnect=()=>{
  socket.closeConnect()
}
const initSocket = () => {
  socket = new WebSocket(socketUrl + '/' + userId)
  socket.onopen = function (event) {
    console.log('Connection opened:', event)
  }

  socket.onmessage = function (event) {
    console.log('Message received:', event)
    receive.value += event.data
  }

  socket.onclose = function (event) {
    console.log('Connection closed:', event)
  }

  socket.onerror = function (error) {
    console.error('WebSocket error:', error)
    
    //五秒后尝试重连
    if (maxTry-- > 0) {
      console.log(maxTry)
      setInterval(initSocket, 5000)
    }
  }
}
</script>

<style></style>
